<?php

namespace App\Domain\Material\Services;

use App\Domain\Dict\Dao\DictDao;
use App\Domain\Dict\Models\DictModel;
use App\Domain\Material\Models\MaterialModel;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\DB;
use App\Exceptions\BadRequestException;
use App\Domain\Material\Dao\MaterialDao;
use Illuminate\Pagination\LengthAwarePaginator;

class MaterialService
{

    /**
     * 物资列表
     * @param $params
     * @return LengthAwarePaginator|Builder[]|Collection
     */
    public function list($params)
    {
        $query = MaterialModel::query()
            ->select('material.*')
            ->where('material.material_dict_code',$params['material_dict_code'])
            ->where('material.state', 1);
        $query = $query->where(function (Builder $query) use ($params) {
            if (isset($params['SN']))
                $query->where('SN', 'like', "%{$params['SN']}%");
            if (isset($params['distribution_status']))
                $query->where('distribution_status', $params['distribution_status']);
            if (isset($params['deliver_status']))
                $query->where('deliver_status', $params['deliver_status']);
            if (isset($params['start_time']))
                $query->where('warehousing_time', '>=', $params['start_time']);
            if (isset($params['end_time']))
                $query->where('warehousing_time', '<=', $params['end_time']);
        });
        if (isset($params['pageSize']) && isset($params['currentPage'])) {
            return $query->paginate($params['pageSize'], ['*'], 'page', $params['currentPage']);
        } else {
            return $query->get();
        }
    }


    public function distributionlist($params)
    {
        $model = MaterialModel::select('material.*', DB::raw('count(*) as num'))->where('distribution_status', '1')->where('state', '1')->where('channel_business_id', $params['channel_business_id'])->groupBy('material_dict_code');
        if (isset($params['name'])) {
            $model = MaterialModel::select('material.*', DB::raw('count(*) as num'))->where('distribution_status', '1')->where('state', '1')->where('channel_business_id', $params['channel_business_id'])->where('name', $params['name'])->groupBy('material_dict_code');

        }
        if (isset($params['pageSize']) && isset($params['currentPage'])) {
            return $model->paginate($params['pageSize'], ['*'], 'page', $params['currentPage']);
        } else {
            return $model->get();
        }
    }

    /**
     * 铺货详情
     * @param $params
     * @return LengthAwarePaginator|Builder[]|Collection
     */
    public function distributioninfo($params)
    {
        $query = MaterialModel::query()
            ->select('material.*')
            ->where('distribution_status', '1')
            ->where('material.state', 1);
        $query = $query->where(function (Builder $query) use ($params) {
            if (isset($params['channel_business_id']))
                $query->where('channel_business_id', $params['channel_business_id']);
            if (isset($params['name']))
                $query->where('name', $params['name']);
        });
        if (isset($params['pageSize']) && isset($params['currentPage'])) {
            return $query->paginate($params['pageSize'], ['*'], 'page', $params['currentPage']);
        } else {
            return $query->get();
        }
    }

    public function findNumAndType()
    {
        $type = DictModel::query()->where('type_code', '10080')->get();
        foreach ($type as $v) {
            $v['num'] = MaterialModel::query()->where('material_dict_code', $v['id'])->count();
            $v['surplus'] = MaterialModel::query()
                ->where('material_dict_code', $v['id'])
                ->Where('distribution_status', '!=', '0')
                ->count();
        }
        return $type;
    }

    public function setType($param)
    {
        $dictDao = new DictDao();
        $dict = $dictDao->findByDictName($param['name']);
        if ($dict) {
            throw new BadRequestException('名称重复');
        }
        if ($param['material_dict_code']) {
            $dict = $dictDao->findByMaterialCode($param['material_dict_code']);
            $data = [
                'name' => $param['name'],
            ];
            $dict = $dictDao->update($dict, $data);
            return $dict;
        } else {
            $res = $dictDao->create([
                'type_code' => '10080',
                'name' => $param['name'],
            ]);
            return $res;
        }
    }

    public function delType($param)
    {
        return DictModel::where('id', $param['id'])->update(['state', '0']);
    }


    public function create($param)
    {
        $materialDao = new MaterialDao();
        $data = $materialDao->create([
            'SN' => $param['SN'],
            'material_dict_code' => $param['material_dict_code'],
            'material_dict' => $param['material_dict'],
            'model' => $param['model'],
            'name' => $param['name'],
            'warehousing_time' => date("Y-m-d H:i:s", time()),
        ]);
        return $data;
    }

    public function ware($param)
    {
        $materialDao = new MaterialDao();
        $SNS = explode(',', $param['SN']);
        foreach ($SNS as $v) {
            $data = $materialDao->create([
                'SN' => $v,
                'material_dict_code' => $param['material_dict_code'],
                'material_dict' => $param['material_dict'],
                'model' => $param['model'],
                'name' => $param['name'],
                'warehousing_time' => date("Y-m-d H:i:s", time()),
            ]);
        }
        return [];
    }

    public function distribution($param)
    {
        $materialDao = new MaterialDao();
        $SNS = explode(',', $param['SN']);
        foreach ($SNS as $v) {
            $material = $materialDao->findBySNAndModel($v, $param['model']);
            if (empty($material)) {
                throw  new BadRequestException('型号不正确');
            }
            $res = [
                'SN' => $v,
                'distribution_status' => '1',
                'signatory' => $param['signatory'],
                'sign_time' => $param['sign_time'],
                'operator' => $param['operator'],
                'operation_time' => date("Y-m-d H:i;s", time()),
                'channel_business_id' => $param['channel_business_id'],
            ];
            $data = $materialDao->update($material, $res);
        }
        return [];
    }

    public function del($SN)
    {
        $SNs = explode(',', $SN);
        $materialDao = new MaterialDao();
        $data = $materialDao->del($SNs);
        return $data;
    }

    public function edit($param)
    {
        $materialDao = new MaterialDao();
        $material = $materialDao->findBySN($param['SN']);
        if ($material) {
            $res = [
                'SN' => $param['SN'],
                'distribution_status' => $param['distribution_status'],
                'deliver_status' => $param['deliver_status'],
                'model' => $param['model'],
                'warehousing_time' => $param['warehousing_time'],
            ];
            $data = $materialDao->update($material, $res);
        }
        return $data;
    }

    public function distributiondel($param)
    {
        $materialDao = new MaterialDao();
        $material = $materialDao->findByDictAndChannelID($param);
        foreach ($material as $v) {
            $data = $materialDao->distributionDel($v['id']);
        }
        return $data;
    }
}
